var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var url=require("url");
var fs   = require("fs");

var index = require('./routes/index');
var users = require('./routes/users');
var upload=require('./routes/upload');
var hybz=require('./routes/hybz');
var partner=require('./routes/partner');

var app = express();




// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//app.engine('.html', require('jade').renderFile);  
//app.set('view engine', 'html');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

var options = {
dotfiles: 'ignore',
etag: false,//不缓存
extensions: ['htm','html','css','png','gif','jpg','js','tpl'],
//index: true,
maxAge: '3600000',
redirect: true,
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now())
}
};

app.use(express.static(path.join(__dirname, 'public'),options));

app.use('/', index);//demo

app.use('/hybz', hybz);//行业标准
app.use('/users', users);
app.use('/upload',upload);
app.use('/partner',partner);
//app.use('/',index);//index


/*
//其他请求处理，js，css，图片等
app.use(function(req,res){
    var pathname = url.parse(req.url).pathname;
	console.log("pathname--------->"+pathname);
    pathwritehead(pathname,req,res)
});
*/


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});






/*
* 说明：路径解析
* 参数：pathname:路径（项目中的绝对路径）
* 作者：王燕
* 日期：2014.6.9
* */
function pathwritehead(pathname,req, res) {
  //  var pathname = __dirname + url.parse(req.url).pathname;
    pathname=__dirname+pathname;
    if (path.extname(pathname) == "") {
        pathname += "/";
    }
    fs.exists(pathname, function (exists) {
        if (exists) {
            switch (path.extname(pathname)) {
                case ".html":
                    res.writeHead(200, {"Content-Type": "text/html"});
                    break;
                case ".htm":
                    res.writeHead(200, {"Content-Type": "text/html"});
                    break;
                case ".js":
                    res.writeHead(200, {"Content-Type": "text/javascript"});
                    break;
                case ".css":
                    res.writeHead(200, {"Content-Type": "text/css"});
                    break;
                case ".gif":
                    res.writeHead(200, {"Content-Type": "image/gif"});
                    break;
                case ".jpg":
                    res.writeHead(200, {"Content-Type": "image/jpeg"});
                    break;
                case ".png":
                    res.writeHead(200, {"Content-Type": "image/png"});
                    break;
                default:
                    res.writeHead(200, {"Content-Type": "application/octet-stream"});
            }

            fs.readFile(pathname, function (err, data) {
                res.end(data);
            });
        } else {
            res.writeHead(404, {"Content-Type": "text/html"});
            res.end("<h1>404 Not Found</h1>");
        }
    });
}

module.exports = app;
